from django.http import JsonResponse, HttpResponse
from django.shortcuts import render

from trade.models import *
from utils.service import my_page
from operator import itemgetter
from trade.model_choices import *
from trade.OperationLog import OperationLog
import datetime
from utils.chardate import chardate


# 实盘策略监控
def live_monitor(request):
    customerid = request.GET.get("customerid")
    return render(request, "live_monitor.html", {"customerid": customerid})


# 实盘监控，筛选策略展示
def LiveStg(request):
    if request.method == "GET":
        stgid_live_list = []
        stgid_list = list(Strategy.objects.using('quantWebDB').filter(liveisdelete=1).values("stgid"))
        stgid_liveapv_list = list(Liveapproval.objects.using('quantWebDB').values("stgid").filter(packstatus="1"))
        for stgid_dic in stgid_list:
            if stgid_dic in stgid_liveapv_list:
                stgid_live_list.append(stgid_dic.get("stgid"))
        return JsonResponse(stgid_live_list, safe=False)


## 监控页面的修改策略参数
def alterpara(request):
    try:
        ruleid = request.POST.get("ruleid")
        paraname = request.POST.get("paraname")
        paravalue = request.POST.get("paravalue")
        paradesc = request.POST.get("paradesc")
        # 实盘参数表
        Ruleprop.objects.using('quantLiveDB').filter(ruleid=int(ruleid), propkey=paraname).update(
            propvalue=paravalue,
            proptype="1",
            provalueitems="1",
            description=paradesc,
        )
        return JsonResponse("y", safe=False)
    except Exception as e:
        print(e)
        return JsonResponse("服务器错误！", safe=False)


## 监控页面的查看风控信息
def stcLiveRiskInfo(request):
    try:
        today = datetime.datetime.now().strftime("%Y%m%d")
        ruleid = request.GET.get("ruleid")
        risk_list = list(
            Stcriskinfo.objects.using("quantLiveDB").filter(ruleid=int(ruleid), orderinsertdate=today).values())
        for item in risk_list:
            item['direction'] = Direction_ModelChoices.get(item['direction'])
            item['settletype'] = LegSettlType_ModelChoices.get(item['settletype'])
            item['risktype'] = RiskType_ModelChoices.get(item['risktype'])
            if (item.get('orderinserttime') is None):
                item['orderinserttime'] = '-1'
        off = request.GET.get('offset', None)
        lim = request.GET.get('limit', None)
        result_list_sorted = sorted(risk_list, key=itemgetter('orderinserttime'), reverse=True)
        result = my_page(result_list_sorted, lim, off)
        return JsonResponse(result, safe=False)
    except Exception as e:
        print(e)
        return HttpResponse(e)


## 监控页面手工录入提交
def LhandInput(request):
    try:
        bondid = request.POST.get("bondcode")
        direction = request.POST.get("direction_val")
        settletype = request.POST.get("speedliqui_val")
        ytm = request.POST.get("tranc")
        netprice = request.POST.get("netprice") if request.POST.get("netprice") else 0
        volume = request.POST.get("vol")
        blocknum = datetime.datetime.now().strftime('%Y%m%d%H%M%S%f')
        transactime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        ruleid = request.POST.get("ruleid")
        rulename = request.POST.get("rulename")
        customerid = request.POST.get("customerid")
        ManualTradeLive.objects.using('quantWebDB').create(
            ruleid=ruleid,
            blocknum=blocknum,
            bondid=bondid,
            direction=direction,
            transactime=transactime,
            ytm=ytm,
            volume=int(volume),
            settletype=int(settletype),
            netprice=netprice,
            customerid=customerid
        )
        # 人工录入 	人工录入：记录人工录入时的策略ID、策略名、录入时间
        dict_manual = {
            'customerid': request.session.get('id', 'noCid'),
            'modular': '1',
            'optfunction': '8',
            'optinfo': '人工录入成功，策略ID：%s，策略名：%s，录入时间：%s' % (ruleid, rulename, chardate()),
            'opttime': chardate(),
        }
        OperationLog.opt_log(dict_manual)
        return HttpResponse("y")
    except Exception as e:
        print(e)
        return HttpResponse(e)
